package ai.mspbots.service.projecta.controller;

import java.util.concurrent.atomic.AtomicLong;

import ai.mspbots.service.projecta.service.FeignCallService;
import ai.mspbots.service.projecta.service.RibbonCallService;
import cn.hutool.core.util.StrUtil;
import io.opentracing.ActiveSpan;
import io.opentracing.Tracer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.skywalking.apm.toolkit.opentracing.SkywalkingTracer;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import ai.mspbots.service.projecta.vo.Result;

import javax.servlet.http.HttpServletRequest;

import static ai.mspbots.service.projecta.config.Constant.SAMPLE_RATE;

@RestController
public class ServiceController {

    private static final Logger logger = LogManager.getLogger(ServiceController.class);
    private AtomicLong counter = new AtomicLong(0);
    private final Tracer tracer = new SkywalkingTracer();
    @Autowired
    private RibbonCallService projectBServiceCall;

    @Autowired
    private FeignCallService feignCallService;

    @RequestMapping(value = "/projectA/{name}")
    @ResponseBody
    @Trace
    public Result hi(@PathVariable(required = false) String name, HttpServletRequest request) {
        logger.info("traceId={}, spanId={}", TraceContext.traceId(), TraceContext.spanId());
        ActiveSpan span = tracer.activeSpan();
        String tenantCode = request.getHeader("tenantCode");
        if (StrUtil.isNotEmpty(tenantCode)) {
            logger.info("tenantCode={}", tenantCode);
            span.setTag("tenantCode", tenantCode);
        }
        if (counter.getAndIncrement() % SAMPLE_RATE == 0) {
            logger.debug("calling /projectA/{name} service");
        }
        projectBServiceCall.call(name);
        feignCallService.call(name);
        return new Result(TraceContext.traceId());
    }

}
